/*
 * Change password of database including backup file encryption.
 *
 * License: LGPL v3
 */
package org.passwordstore.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.passwordstore.Resource;

/**
 *
 * @author thotheolh
 */
public class ChangePassword {

    private Resource res;

    public ChangePassword(Resource res) {
        this.res = res;
    }

    public boolean doChangePassword(String password, File targetFile) {
        if (changeDBPassword(password)) {
            return changeBackupPassword(password,targetFile);
        } else {
            return false;
        }
    }

    private boolean changeDBPassword(String password) {
        return res.getSql().changeDBPassword(password);
    }

    private boolean changeBackupPassword(String password,File file) {
        //sample
        StringBuffer buff = null;
        StringBuffer decrypt = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String str;
            br.readLine();
            str = br.readLine(); //Reads in the delete all statement
            buff.append(str);
            String p = String.valueOf(res.getPassword());
            byte[] passBytes = res.getAescrypt().hashpwd(p);
            while ((str = br.readLine()) != null) {
                decrypt.append(str);
                System.out.println("Read in: " + str);
            }
            br.close();
            buff.append(res.getAescrypt().ByteToString(res.getAescrypt().decryptFile(res.getAescrypt().HexToByte(decrypt.toString()), passBytes)));
        } catch (IOException ex) {
            Logger.getLogger(Restore.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;//
    }
}
